package com.ypx.ec.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONPathException;
import com.ypx.ec.common.to.es.SkuEsModel;
import com.ypx.ec.search.config.EsSearchConfig;
import com.ypx.ec.search.constant.EsConstant;
import com.ypx.ec.search.service.EsSearchService;
import com.ypx.ec.search.vo.SearchParamVo;
import com.ypx.ec.search.vo.SearchResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class EsSearchServiceImpl implements EsSearchService {
    @Autowired
    RestHighLevelClient client;

    @Override // ProductSaveServiceImpl
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        // 1.给ES建立一个索引 product
        BulkRequest bulkRequest = new BulkRequest();
        // 2.构造保存请求
        for (SkuEsModel esModel : skuEsModels) {
            // 设置es索引
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            // 设置索引id
            indexRequest.id(esModel.getSkuId().toString());
            // json格式
            String jsonString = JSON.toJSONString(esModel);
            indexRequest.source(jsonString, XContentType.JSON);
            // 添加到文档
            bulkRequest.add(indexRequest);
        }
        // bulk批量保存
        BulkResponse bulk = client.bulk(bulkRequest, EsSearchConfig.COMMON_OPTIONS);
        // TODO 是否拥有错误
        boolean hasFailures = bulk.hasFailures();
        if(hasFailures){
            List<String> collect = Arrays.stream(bulk.getItems()).map(item -> item.getId()).collect(Collectors.toList());
            log.error("商品上架错误：{}",collect);
        }
        return hasFailures;
    }

    @Override
    public SearchResult productSearch(SearchParamVo searchParamVo) throws IOException {
        SearchRequest searchRequest=buildSearchRequest(searchParamVo);
        SearchResponse search = client.search(searchRequest, EsSearchConfig.COMMON_OPTIONS);
        SearchResult searchResult=resolveResult(search,searchParamVo);
        return searchResult;
    }

    private SearchRequest buildSearchRequest(SearchParamVo searchParamVo) throws IOException {
        SearchSourceBuilder sourceBuilder=new SearchSourceBuilder();
        BoolQueryBuilder boolQuery=buildBoolQuery(searchParamVo);
        sourceBuilder.query(boolQuery);
        /**
         * 分页
         */
        if(StringUtils.isNotEmpty(searchParamVo.getSort())){
            String sort=searchParamVo.getSort();
            String[] sorts=sort.split("_");
            if(SortOrder.ASC.toString().equals(sorts[1])){
                sourceBuilder.sort(sorts[0],SortOrder.ASC);
            }else if(SortOrder.DESC.toString().equals(sorts[1])){
                sourceBuilder.sort(sorts[0],SortOrder.DESC);
            }

        }
        /**
         * 排序
         */
        sourceBuilder.from((searchParamVo.getPageNum()-1)*EsConstant.PRODUCT_PAGESIZE);
        sourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);
        /**
         * 高亮
         */
        if(StringUtils.isNotEmpty(searchParamVo.getKeyword())){
            HighlightBuilder hight=new HighlightBuilder();
            hight.field("skuTitle");
            hight.preTags("<font color='red'>");
            hight.postTags("</font>");
            sourceBuilder.highlighter(hight);
        }
        /**
         * 聚合查询
         */
        //聚合分析
        //1.品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size(50);
        //1.1品牌聚合的子聚合
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        sourceBuilder.aggregation(brand_agg);
        //2.分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(20);
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        sourceBuilder.aggregation(catalog_agg);
        //3.属性聚合(嵌入式聚合)
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        //聚合出当前所有的attr_id
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        //聚合分析当前attr_id对应的名字
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        //聚合分析当前attr_id对应的所有可能的属性值attrValue
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        attr_agg.subAggregation(attr_id_agg);
        sourceBuilder.aggregation(attr_agg);



        SearchRequest searchRequest=new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX},sourceBuilder);

        return searchRequest;
    }

    private BoolQueryBuilder buildBoolQuery(SearchParamVo searchParamVo) {
        BoolQueryBuilder boolQuery=QueryBuilders.boolQuery();
        /**
         * sku
         * 商品名称
         */
        if(StringUtils.isNotEmpty(searchParamVo.getKeyword())){
            boolQuery.must(QueryBuilders.matchQuery("skuTitle",searchParamVo.getKeyword()));
        }
        /**
         * 分类
         */
        if(searchParamVo.getCatalog3Id()!=null){
            boolQuery.filter(QueryBuilders.termQuery("catalogId",searchParamVo.getCatalog3Id()));
        }
        /**
         * 品牌
         */
        if(searchParamVo.getBrandId()!=null){
            boolQuery.filter(QueryBuilders.termQuery("brandId",searchParamVo.getBrandId()));
        }
        /**
         * 库存true:false
         */
        boolQuery.filter(QueryBuilders.termQuery("hasStock",searchParamVo.getHasStock()==1));
        if(StringUtils.isNotEmpty(searchParamVo.getSkuPrice())){
            String[] strings=searchParamVo.getSkuPrice().split("_");
            if(strings.length==1){
                String skuPrice=searchParamVo.getSkuPrice();
                if(skuPrice.charAt(0)=='_'){
                    boolQuery.filter(QueryBuilders.rangeQuery("skuPrice").lt(strings[0]));
                }else{
                    boolQuery.filter(QueryBuilders.rangeQuery("skuPrice").gt(strings[0]));
                }
            }else{
                boolQuery.filter(QueryBuilders.rangeQuery("skuPrice").from(strings[0]).to(strings[1]));
            }
        }
        if(searchParamVo.getAttrs()!=null && searchParamVo.getAttrs().size()!=0){

            for (String attrStr : searchParamVo.getAttrs()) {
                //attrs=1_5寸:8寸&attrs=2_16G:8G
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                String[] s = attrStr.split("_");
                String attrId = s[0];//属性id
                String[] attrValues = s[1].split(":");//检索的属性值
                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                //每一个必须得生成一个nested查询
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }

        }

        return boolQuery;
    }

    private SearchResult resolveResult(SearchResponse response,SearchParamVo searchParamVo) {
        SearchResult searchResult=new SearchResult();
        SearchHits hits = response.getHits();
        //设置总数
        Long total=hits.getTotalHits().value;
        searchResult.setTotal(total);
        //设置总页数
        Long totalPage=(total+1)/EsConstant.PRODUCT_PAGESIZE;
        searchResult.setTotalPage(totalPage);
        searchResult.setPageNum(searchParamVo.getPageNum());
        //skuModel
        SearchHit[] searchHits = hits.getHits();
        List<SkuEsModel> products=new ArrayList<>();
        if(searchHits!=null && searchHits.length!=0){
            for (SearchHit searchHit : searchHits) {
                String sourceAsString = searchHit.getSourceAsString();
                SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                if (!StringUtils.isEmpty(searchParamVo.getKeyword())) {
                    //设置高亮内容
                    HighlightField skuTitle = searchHit.getHighlightFields().get("skuTitle");
                    String string = skuTitle.getFragments()[0].string();
                    skuEsModel.setSkuTitle(string);
                }
                products.add(skuEsModel);
            }
        }
        searchResult.setProducts(products);

        Aggregations aggregations = response.getAggregations();
        /**
         * 封装catalog
         */
        ParsedLongTerms catalog_agg = aggregations.get("catalog_agg");
        List<? extends Terms.Bucket> buckets = catalog_agg.getBuckets();
        List<SearchResult.CatalogVo> catalogs=new ArrayList<>();
        if(buckets.size()!=0 && buckets!=null){
            for (Terms.Bucket bucket : buckets) {
                SearchResult.CatalogVo catalogVo=new SearchResult.CatalogVo();
                catalogVo.setCatalogId(Long.parseLong(bucket.getKeyAsString()));
                ParsedStringTerms catalog_name_agg=bucket.getAggregations().get("catalog_name_agg");
                catalogVo.setCatalogName(catalog_name_agg.getBuckets().get(0).getKeyAsString());
                catalogs.add(catalogVo);


            }
        }
        searchResult.setCatalogs(catalogs);

        /**
         * 封装brands
         */
        ParsedLongTerms brand_agg = aggregations.get("brand_agg");
        buckets = brand_agg.getBuckets();
        List<SearchResult.BrandVo> brands=new ArrayList<>();
        if(buckets.size()!=0 && buckets!=null){
            for (Terms.Bucket bucket : buckets) {
                SearchResult.BrandVo brandVo=new SearchResult.BrandVo();
                brandVo.setBrandId(Long.parseLong(bucket.getKeyAsString()));
                ParsedStringTerms brand_img_agg=bucket.getAggregations().get("brand_img_agg");
                ParsedStringTerms brand_name_agg=bucket.getAggregations().get("brand_name_agg");
                brandVo.setBrandName(brand_name_agg.getBuckets().get(0).getKeyAsString());
                brandVo.setBrandImg(brand_img_agg.getBuckets().get(0).getKeyAsString());
                brands.add(brandVo);

            }
        }

        searchResult.setBrands(brands);
        /**
         * 封装attrs
         */
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        ParsedNested attr_agg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");//根据返回值确定数据类ParsedLongTerms，ParsedNested
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            //1.得到属性的id
            long attrId = bucket.getKeyAsNumber().longValue();
            //2.得到属性的名字
            String attrName = ((ParsedStringTerms) bucket.getAggregations().get("attr_name_agg")).getBuckets().get(0).getKeyAsString();
            //3.得到属性的所有值
            List<String> attrValues = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg")).getBuckets().stream().map(item -> {
                String keyAsString = ((Terms.Bucket) item).getKeyAsString();
                return keyAsString;
            }).collect(Collectors.toList());
            attrVo.setAttrId(attrId);
            attrVo.setAttrName(attrName);
            attrVo.setAttrValue(attrValues);
            attrVos.add(attrVo);
        }
        searchResult.setAttrs(attrVos);


        return searchResult;
    }

}
